package com.tymoshenko.seabattle.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.tymoshenko.seabattle.client.ClientFactory;
import com.tymoshenko.seabattle.client.rpc.shipplacement.ShipPlacementService;
import com.tymoshenko.seabattle.client.rpc.shipplacement.ShipPlacementServiceAsync;
import com.tymoshenko.seabattle.client.view.DashboardView;
import com.tymoshenko.seabattle.shared.model.domain.Board;
import com.tymoshenko.seabattle.shared.model.domain.Player;
import com.tymoshenko.seabattle.shared.model.domain.Point;

import java.util.Map;

/**
 * @author Yakiv Tymoshenko
 * @since 07.02.13
 */
public class ShipPlacementPresenterImpl implements DashboardView.ShipPlacementPresenter {

    private DashboardView dashboardView;
    private ClientFactory clientFactory;
    private ShipPlacementServiceAsync remoteService;

    public ShipPlacementPresenterImpl(DashboardView dashboardView, ClientFactory clientFactory) {
        this.dashboardView = dashboardView;
        this.clientFactory = clientFactory;
        remoteService = GWT.create(ShipPlacementService.class);
        dashboardView.setShipPlacementPresenter(this);
    }

    public void placeShips() {
        dashboardView.repaintTable(dashboardView.getOwnBoard());
        dashboardView.repaintTable(dashboardView.getOpponentBoard());

        if (remoteService == null) {
            remoteService = GWT.create(ShipPlacementService.class);
        }
        AsyncCallback<Player[]> callback = new AsyncCallback<Player[]>() {
            public void onFailure(Throwable caught) {
                Window.alert(caught.getMessage());
            }

            public void onSuccess(Player[] result) {
                clientFactory.setPlayer1(result[0]);
                clientFactory.setPlayer2(result[1]);

                displayShips(dashboardView.getOwnBoard(), clientFactory.getPlayer1().getBoard());
            }
        };
        remoteService.placeShips(clientFactory.getAccount1(), clientFactory.getAccount2(), callback);
    }

    private void displayShips(FlexTable table, Board board) {
        for (Map.Entry<Point, Board.Status> entry : board.getFields().entrySet()) {
            if (entry.getValue() == Board.Status.DECK) {
                table.getCellFormatter().setStyleName(entry.getKey().getRow() - 1, entry.getKey().getCol() - 1, "gameBoardCellShip");
            }
        }
    }
}
